package com.echo.servlet;

import com.echo.entity.User;
import com.echo.util.SessionUtils;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.TemplateEngine;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

/**
 * 基础Servlet类，提供通用功能，供其他具体Servlet继承
 */
public class BaseServlet extends HttpServlet {
    // 设置请求编码（POST提交）
    protected void setRequestEncoding(HttpServletRequest request) {
        try {
            request.setCharacterEncoding("UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 校验登录状态（未登录则重定向到登录页）
    protected boolean checkLogin(HttpServletRequest request, HttpServletResponse response) throws IOException {
        User loginUser = SessionUtils.getCurrentUser(request);
        if (loginUser == null) {
            response.sendRedirect(request.getContextPath() + "/login.html");
            return false; // 未登录
        }
        return true; // 已登录
    }
    
    // 校验管理员权限（不是管理员则重定向到首页，提示无权限）
    protected boolean checkAdmin(HttpServletRequest request, HttpServletResponse response) throws IOException {
        User loginUser = SessionUtils.getCurrentUser(request);
        if (loginUser == null) {
            response.sendRedirect(request.getContextPath() + "/login.html");
            return false; // 未登录
        }
        
        if (loginUser.getRole() != 1) { // 1表示管理员，0表示普通用户
            request.setAttribute("errorMsg", "权限不足，只有管理员可以进行此操作");
            response.sendRedirect(request.getContextPath() + "/");
            return false; // 不是管理员
        }
        return true; // 是管理员
    }

    /**
     * 转发到指定页面
     * @param request 请求对象
     * @param response 响应对象
     * @param path 页面路径
     */
    protected void forward(HttpServletRequest request, HttpServletResponse response, String path) {
        try {
            // 获取ServletContext中的模板引擎
            ServletContext servletContext = getServletContext();
            TemplateEngine templateEngine = (TemplateEngine) servletContext.getAttribute("thymeleafTemplateEngine");
            
            if (templateEngine != null) {
                // 如果有模板引擎，使用Thymeleaf渲染
                // 创建WebContext
                WebContext context = new WebContext(request, response, servletContext);
                
                // 复制请求属性到WebContext
                Enumeration<String> attributeNames = request.getAttributeNames();
                while (attributeNames.hasMoreElements()) {
                    String name = attributeNames.nextElement();
                    context.setVariable(name, request.getAttribute(name));
                }
                
                // 复制会话属性到WebContext
                HttpSession session = request.getSession(false);
                if (session != null) {
                    Enumeration<String> sessionAttributeNames = session.getAttributeNames();
                    while (sessionAttributeNames.hasMoreElements()) {
                        String name = sessionAttributeNames.nextElement();
                        context.setVariable(name, session.getAttribute(name));
                    }
                }
                
                // 处理路径（保留开头的斜杠）
                String templatePath = path;
                // 注意：根据Thymeleaf配置，可能需要或不需要去掉.html后缀
                // 为确保兼容性，我们保留.html后缀
                // 如果Thymeleaf配置要求去掉后缀，这里会需要修改
                
                // 设置响应内容类型
                response.setContentType("text/html;charset=UTF-8");
                
                // 使用模板引擎渲染页面
                templateEngine.process(templatePath, context, response.getWriter());
            } else {
                // 如果模板引擎不存在，使用传统的转发
                request.getRequestDispatcher(path).forward(request, response);
            }
        } catch (Exception e) {
            // 记录异常信息
            System.err.println("页面转发错误: " + e.getMessage());
            e.printStackTrace();
            try {
                // 重置响应
                if (!response.isCommitted()) {
                    response.reset();
                    response.setContentType("text/html;charset=UTF-8");
                    PrintWriter out = response.getWriter();
                    out.println("<html><head><title>系统错误</title></head><body>");
                    out.println("<h1>系统错误</h1>");
                    out.println("<p>处理请求时发生错误，请稍后再试。</p>");
                    out.println("<p><a href='" + request.getContextPath() + "/'>返回首页</a></p>");
                    out.println("</body></html>");
                    out.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 空实现，由子类重写
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}